package com.zhiyin.seal.task;

import com.zhiyin.seal.entity.bo.MyApprovalBo;
import com.zhiyin.seal.entity.dto.WebSocketRequestDTO;
import com.zhiyin.seal.entity.vo.WebSocketMessageVo;
import com.zhiyin.seal.service.ApplyService;
import com.zhiyin.seal.websocket.WebsocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class WebSocketNoticeTask {

    @Autowired
    ApplyService applyService;

    @Scheduled(fixedDelay = 1000 * 5)
    public void postNotice(){
        // 获取系统当前待我审批的前100条数据
        List<MyApprovalBo> approvalBoList = applyService.getWaitApprovalList();
        if(approvalBoList.size() > 0){
            // 发送待我审批消息
            sendWaitMyApproval(approvalBoList);
            // 更新通知状态
            List<Long> idList = approvalBoList.stream().map(MyApprovalBo::getId).collect(Collectors.toList());
            if(idList.size() > 0){
                applyService.updateWaiteApproval(idList);
            }
        }
        // 获取用户可用单据
        List<Long> stampUserList = applyService.getMyAvailableApply();
        if(stampUserList.size() > 0){
            // 发送可用单据消息
            sendMyAvailableApply(stampUserList);
        }
    }

    /**
     * 发送待我审批消息
     * @param approvalBoList
     */
    private void sendWaitMyApproval(List<MyApprovalBo> approvalBoList){
        for (MyApprovalBo approvalBo : approvalBoList){
            WebSocketMessageVo webSocketMessageVo = new WebSocketMessageVo();
            webSocketMessageVo.setOperateType(WebSocketRequestDTO.WAIT_APPROVAL);
            webSocketMessageVo.setHasApproval(true);
            WebsocketServer.sendDataByUserId(approvalBo.getUserId().toString(),webSocketMessageVo);
        }
    }

    /**
     * 发送可用单据消息
     * @param stampUserList
     */
    private void sendMyAvailableApply(List<Long> stampUserList){
        for (Long stampUser : stampUserList){
            WebSocketMessageVo webSocketMessageVo = new WebSocketMessageVo();
            webSocketMessageVo.setOperateType(WebSocketRequestDTO.AVAILABLE_APPLY);
            webSocketMessageVo.setAvailableApply(true);
            WebsocketServer.sendDataByUserId(stampUser.toString(),webSocketMessageVo);
        }
    }


}
